<?php 
define('DISABLEDEFENSE', true);
define('DISABLEXSSCHECK', true);
require '../../../../class/class_core.php';
C::app()->init();

require_once "WxPay.Config.php";
require_once "lib/WxPay.Api.php";
define('BOAN_PAYMENT_NAME', 'plugin/boan_buycredit');
global $_G;
$VUE = '$';
if(strpos($_G['siteurl'], 'source') !== FALSE){
    $_G['siteurl'] = substr($_G['siteurl'],0,strpos($_G['siteurl'], 'source'));
}
try{   
    $order_id = dhtmlspecialchars($_GET['order_id']);
    if(empty($order_id) || !($order = C::m('#boan_payment#payment')->getOrder($order_id))){
        throw new Exception(lang(BOAN_PAYMENT_NAME, 'order_err4'));    
    }    
    if($order['status'] != 0){
        throw new Exception(lang(BOAN_PAYMENT_NAME, 'order_err6'));
    }    
    $biz_content=[
        'out_trade_no' => $order_id,
        'total_amount' => $order['amount'],
        'subject' => $order['subject'],
    ];
    $backurl = '';
    if($order['return_url']){
        $backurl = $_G['siteurl'].$order['return_url'];
    }else{
        $backurl = $_G['siteurl'].'home.php?mod=spacecp&ac=plugin&id=boan_payment:user_order';
    }
    $biz_content = boan_paymentBase::iconv($biz_content,CHARSET,'utf-8');
    $tools = new JsApiPay();
    $openId = $tools->GetOpenid();   
    $input = new WxPayUnifiedOrder();
    $input->SetBody($biz_content['subject']);
    $input->SetOut_trade_no($biz_content['out_trade_no']);
    $input->SetTotal_fee(intval($biz_content['total_amount']*100));
    $input->SetTime_start(date("YmdHis"));
    $input->SetTime_expire(date("YmdHis", time() + 600));
    $input->SetNotify_url($_G['siteurl'].'source/plugin/boan_payment/pay/wxpay/notify.php');
    $input->SetProduct_id($biz_content['out_trade_no']);
    $input->SetTrade_type("JSAPI");
    $input->SetOpenid($openId);

    $order1 = WxPayApi::unifiedOrder($tools->Config, $input);
    if(empty($order1['prepay_id'])){
        throw new Exception(json_encode(boan_paymentBase::iconv($order1,'utf-8',CHARSET),JSON_UNESCAPED_UNICODE));
    }
    $jsApiParameters = $tools->GetJsApiParameters($order1);
    $order['create_time'] = dgmdate($order['create_time']);
    $order['expire_time'] = dgmdate($order['expire_time']);
    
    include template('boan_payment:wxpayCashier');
}catch (Exception $e){
    throw new Exception(json_encode(boan_paymentBase::iconv($e,'utf-8',CHARSET),JSON_UNESCAPED_UNICODE));
}




class JsApiPay{
    public $Config;
    private $Vars;
    function __construct(){
        global $_G;
        if(empty($_G['cache']['plugin'])){
            loadcache('plugin');
        }
        
        $vars = $_G['cache']['plugin']['boan_payment'];
        $this->Vars = $vars;
        $this->Config = new WxPayConfig($vars);
        
    }
    public function GetOpenid()
    {
        global $_G;
        //通过code获得openid
        $openid = getcookie('boan_payment_openid');
        if(empty($openid)){
            if (!isset($_GET['code'])){
                //触发微信返回code码
                $baseUrl = urlencode($_G['siteurl'].$_SERVER['REQUEST_URI']);
                $url = $this->_CreateOauthUrlForCode($baseUrl);
                Header("Location: $url");
                exit();
            } else {
                //获取code码，以获取openid
                $code = $_GET['code'];
                $openid = $this->getOpenidFromMp($code);
                dsetcookie('boan_payment_openid', $openid, 86400 * 30);
            }
        }
        return $openid;
    }
    
    public function GetOpenidFromMp($code)
    {
        $url = $this->__CreateOauthUrlForOpenid($code);
        
        //初始化curl
        $ch = curl_init();
        $curlVersion = curl_version();
        $config = $this->Config;
        $ua = "WXPaySDK/3.0.9 (".PHP_OS.") PHP/".PHP_VERSION." CURL/".$curlVersion['version']." "
            .$config->GetMerchantId();
            
            //设置超时
            curl_setopt($ch, CURLOPT_TIMEOUT, $this->curl_timeout);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
            curl_setopt($ch, CURLOPT_USERAGENT, $ua);
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            
            $proxyHost = "0.0.0.0";
            $proxyPort = 0;
            $config->GetProxy($proxyHost, $proxyPort);
            if($proxyHost != "0.0.0.0" && $proxyPort != 0){
                curl_setopt($ch,CURLOPT_PROXY, $proxyHost);
                curl_setopt($ch,CURLOPT_PROXYPORT, $proxyPort);
            }
            //运行curl，结果以jason形式返回
            $res = curl_exec($ch);
            curl_close($ch);
            //取出openid
            $data = json_decode($res,true);
            if(empty($data['openid'])){
                throw new Exception('Can not get a openid!');
            }
            
            $this->data = $data;
            $openid = $data['openid'];
            return $openid;
    }
    
    private function _CreateOauthUrlForCode($redirectUrl)
    {
        $config = $this->Config;
        $urlObj["appid"] = $config->GetAppId();
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_base";
        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }
    
    private function __CreateOauthUrlForOpenid($code)
    {
        $config = $this->Config;
        $urlObj["appid"] = $config->GetAppId();
        $urlObj["secret"] = $config->GetAppSecret();
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }
    
    public function GetJsApiParameters($UnifiedOrderResult)
    {
        if(!array_key_exists("appid", $UnifiedOrderResult)
            || !array_key_exists("prepay_id", $UnifiedOrderResult)
            || $UnifiedOrderResult['prepay_id'] == "")
        {
            throw new WxPayException("params_error");
        }
        
        $jsapi = new WxPayJsApiPay();
        $jsapi->SetAppid($UnifiedOrderResult["appid"]);
        $timeStamp = time();
        $jsapi->SetTimeStamp("$timeStamp");
        $jsapi->SetNonceStr(WxPayApi::getNonceStr());
        $jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']);
        
        $config = $this->Config;;
        $jsapi->SetPaySign($jsapi->MakeSign($config));
        $parameters = json_encode($jsapi->GetValues(),JSON_UNESCAPED_UNICODE);
        return $parameters;
    }
    
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }
        
        $buff = trim($buff, "&");
        return $buff;
    }
    
}